package com.metis.document.parse.dialog.pipeline.impl;

import com.metis.document.parse.dialog.pipeline.TextPostProcess;
import com.metis.document.parse.dialog.utils.SymbolUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.jetbrains.annotations.NotNull;
import org.springframework.stereotype.Component;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 图片题注处理器
 */
@Slf4j
@Component
public class FigureCaptionPostProcess implements TextPostProcess {

    private static final String rex = "(面|样|见|如|造|\\()图(\\d{0,3}|\\()";
    private static final Pattern blackListPattern = Pattern.compile(rex);
    private static final String jh = "。";

    @Override
    public String process(@NotNull String input) {
        if (StringUtils.isEmpty(input)) {
            return input;
        }

        String[] inputSplit = input.split(jh);
        StringBuilder sb = new StringBuilder();
        for (String si : inputSplit) {
            Matcher matcher = blackListPattern.matcher(si);
            if (matcher.find()) {
                int start = matcher.start();
                // 向前搜索标点符号
                int punctuationIndex = SymbolUtil.findNearestPunctuation(si, start);
                if (punctuationIndex != -1) {
                    sb.append(si.substring(0, punctuationIndex));
                } else {
                    log.info("当前位置前面没有标点符号");
                }

                //向后搜索标点符号
                int punctuationEnd = SymbolUtil.findNextPunctuation(si, start);
                if (punctuationEnd != -1) {
                    sb.append(si.substring(punctuationEnd));
                } else {
                    log.info("当前位置后面没有标点符号");
                }

                continue;
            }
            if (input.contains("。"))
                sb.append(si).append(jh);
            else
                sb.append(si);
        }
        return sb.toString();
    }
}
